package com.tarena.lbs.basic.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.xml.internal.bind.v2.TODO;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.basic.web.repository.UserGroupRepository;
import com.tarena.lbs.basic.web.repository.UserRepository;
import com.tarena.lbs.basic.web.repository.UserTagsRepository;
import com.tarena.lbs.basic.web.utils.AuthenticationContextUtils;
import com.tarena.lbs.common.basic.util.RandomUserName;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.dto.UserDTO;
import com.tarena.lbs.pojo.basic.param.UserParam;
import com.tarena.lbs.pojo.basic.po.UserPO;
import com.tarena.lbs.pojo.basic.po.UserTagsPO;
import com.tarena.lbs.pojo.basic.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserTagsRepository userTagsRepository;
    @Autowired
    private UserGroupRepository userGroupRepository;

    public void doRegister(UserParam param) throws BusinessException {
        //1.checkPhoneReuse 检查电话重复问题
        checkPhoneReuse(param.getPhone());
        //2.封装po 补充必要参数属性,调用save写入数据
        UserPO poParam=param2po(param);
        userRepository.save(poParam);
    }

    private UserPO param2po(UserParam param) {
        //给UserPO仓储层入仓 补充几个属性
        UserPO poParam=new UserPO();
        BeanUtils.copyProperties(param,poParam);
        //1.状态 status 0刚注册 1已绑定标签
        poParam.setStatus(0);
        //2.nickname username 随机值
        poParam.setNickName(RandomUserName.createRandomName());
        poParam.setUserName(param.getNickName());
        //3.注册时间 regTime
        poParam.setRegTime(new Date());
        return poParam;
    }

    private void checkPhoneReuse(String phone) throws BusinessException {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("phone",phone);
        long count = userRepository.count(queryWrapper);
        Asserts.isTrue(count>0,new BusinessException("-2","手机号重复使用"));
    }

    public UserDTO detail(Integer userId){
        UserPO userPo = userRepository.getById(userId);
        UserDTO dto=null;
        if (userPo!=null){
            dto=new UserDTO();
            BeanUtils.copyProperties(userPo,dto);
        }
        return dto;
    }
    public UserVO detail() throws BusinessException {
        //1.线程ThreadLocal工具
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","认证解析失败"));
        //2.使用userId查询数据库
        Integer userId = userPrinciple.getId();
        UserPO userPo = userRepository.getById(userId);
        //将userPO转化成userVO
        UserVO vo=new UserVO();
        BeanUtils.copyProperties(userPo,vo);
        return vo;
    }

    public List<Integer> getUserGroups(Integer userId, Integer businessId) {
        //使用单表的 仓储层 避免复杂关联查询 因为会锁表
        //1.不能使用userId直接检查人群,但是可以使用userId查询绑定关联的标签
        //select * from lbs_user_tags where user_id=? 1,2,3,4,5 List<Integer>
        List<Integer> tagIds=getUserTagIdsByUserId(userId);
        //2.使用标签id集合 与businessId 查询用户所属人群列表
        List<Integer> groupIds= getUserGroupsByTagsAndBusiness(tagIds,businessId);
        return groupIds;
    }

    private List<Integer> getUserGroupsByTagsAndBusiness(List<Integer> tagIds, Integer businessId) {
        //select id from lbs_user_group where business_id=?
        //and (FIND_IN_SET(?,tag_ids) OR FIND_IN_SET(?,tag_ids));
        return userGroupRepository.getUserGroupsByTagsAndBusiness(tagIds,businessId);
    }

    private List<Integer> getUserTagIdsByUserId(Integer userId) {
        //select * from lbs_user_tags where user_id=?
        QueryWrapper<UserTagsPO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<UserTagsPO> pos = userTagsRepository.list(queryWrapper);
        List<Integer> tagIds=null;
        if (pos!=null&&pos.size()>0){
            tagIds=pos.stream().map(po->{
                return po.getTagId();
            }).collect(Collectors.toList());
        }
        log.info("用户标签查询:{}",tagIds);
        return tagIds;
    }
}
